//
//  LoginRegisterInfoController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/7.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import Reusable
import SnapKit
import JFPopup
import Localize_Swift
import SwiftyUserDefaults

class LoginRegisterInfoController: BaseViewController {
    
    var mobile: String
    // 国家，0：中国，1：俄罗斯，2：
    var country: Int
    var password: String
    var captcha: String
    var inviter: String
    var email: String?
    var base64: String?
    init(mobile: String, country: Int, password: String, captcha: String, inviter: String, email: String?, base64: String?) {
        self.mobile = mobile
        self.country = country
        self.password = password
        self.captcha = captcha
        self.inviter = inviter
        self.email = email
        self.base64 = base64
        super.init(nibName: nil, bundle: nil)
    }
    
    private var city: Int = -1
    private var identityId: Int = -1
    private var nickname: String = ""
    private var avatarUrl: String = ""
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.backgroundColor = .clear
        // 滚动时隐藏键盘
        scrollView.keyboardDismissMode = .onDrag
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        view.addSubview(scrollView)
        return scrollView
    }()
    
    // 提交
    private lazy var submitView: LoginRegisterInfoSubmitView = {
        LoginRegisterInfoSubmitView.loadFromNib()
    }()
    
    // 选择国家
    private lazy var countryView: LoginRegisterCountryView = {
        LoginRegisterCountryView.loadFromNib()
    }()
    
    // 所在地区
    private lazy var areaView: LoginRegisterAreaView = {
        LoginRegisterAreaView.loadFromNib()
    }()
    
    var cityList: [LoginCityModel] = []
    lazy var cityView: CountryPickerView = {
        CountryPickerView.loadFromNib()
    }()
    
    // 选择身份
    private lazy var identityView: LoginRegisterIdentityView = {
        LoginRegisterIdentityView.loadFromNib()
    }()
    
    // 填写公司
    private lazy var companyView: LoginRegisterCompanyView = {
        LoginRegisterCompanyView.loadFromNib()
    }()
    
    // 上传头像
//    private lazy var avatarView: LoginRegisterAvatarView = {
//        LoginRegisterAvatarView.loadFromNib()
//    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initNav()
        initUI()
        getSelectedCityList(isShow: false)
    }
    
//    @objc func uploadAvatar(image: UIImage) {
//        
//#if DEBUG
//        let imageData = image.jpegData(compressionQuality: 0.5)
//        let imageSize = imageData?.count ?? 0
//        // 文件大小单位为kb
//        let imageSizeInKB = Double(imageSize) / 1024.0
//        xLog("选择上传图片尺寸 \(image.size) 的大小: \(imageSizeInKB) kb > \(imageSizeInKB / 1024.0) m " )
//#endif
//        
//        YLHUD.showLottie()
//        let object = AliOSSObject.init(image)
//        AliOSSUtil.shared.uploadSingleObject(object) { bytesSent, totalBytesSent, totalBytesExpectedToSend in
//            let progress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
//            xLog("[上传] 图片上传进度 \(Int(progress*100))")
//        } completion: { object, error in
//            DispatchQueue.main.async { [self] in
//                YLHUD.hideHUD()
//                if error != nil {
//                    YLHUD.showHint(.error, "上传失败")
//                    xLog(error)
//                    avatarUrl = ""
//                    avatarView.avatarButton.setImage("ic_login_upload_avatar".toImage, for: .normal)
//                    return
//                }
//                xLog(object.url)
//                avatarUrl = object.url
//                avatarView.avatarButton.setImage(image, for: .normal)
//            }
//        }
//    }
//    
//    @objc func selectImageFromLibrary() {
//        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
//            let imagePicker = UIImagePickerController()
//            imagePicker.delegate = self
//            imagePicker.sourceType = .photoLibrary
//            imagePicker.allowsEditing = true // 允许编辑图片（可选）
//            present(imagePicker, animated: true, completion: nil)
//        } else {
//            print("没有可用的相册源")
//        }
//    }
    
    @objc func registerAction() {
        // 注册
        if country == -1 {
            YLHUD.showMessage("选择国家".localized(.login))
            return
        }
        
        if city < 0 {
            YLHUD.showMessage("请选择所在地区".localized(.login))
            return
        }
        
        if identityId == -1 {
            YLHUD.showMessage("选择身份".localized(.login))
            return
        }
        
        if nickname.isEmpty {
            YLHUD.showMessage("公司/个人名称".localized(.login))
            return
        }
        
//        if avatarUrl == nil {
//            YLHUD.showMessage("上传用户头像".localized(.login))
//            return
//        }
        
        YLHUD.showLottie()
        let target = LoginAPI.register(
            mobile: mobile,
            captcha: captcha,
            password: password,
            country: country,
            name: nickname,
            avatar: avatarUrl,
            identityId: identityId,
            cityId: city,
            inviterCode: inviter,
            email: email)
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                let dataDictionary = res.dataDictionary
                // 清空注册时的邀请码
                Defaults[\.inviterCode] = ""
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                YLRequest.request(FinAuthAPI.uploadFaceFile(mobile: mobile, imageBase64: self.base64 ?? ""))
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu)) {
                    self.navigationController?.popToRootViewController(animated: true)
                }
                
            case .failure(let err):
                let dataDictionary = err.dataDictionary
                xLog("dataDictionary \(dataDictionary as NSDictionary)")
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
            }
        }
        
    }
    
    func getSelectedCityList(isShow: Bool) {
        view.endEditing(true)
        
        let countryType = LanguageManager.isLanguageZH ? 0: 1
        
        let target = LoginAPI.cityList(country: countryType, pid: 0, isPort: true)
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                
                let dataArray = res.dataArray
                
                // 过滤掉请选择
                let list = JsonUtil.modelsFromArray(dataArray, LoginCityModel.self).filter({ $0.id != -2 })
                
                list.forEach { countryModel in
                    // 国家
                    countryModel.level = 0
                    countryModel.children.forEach { provinceModel in
                        // 省
                        provinceModel.pid = countryModel.id
                        provinceModel.level = 1
                        provinceModel.children.forEach { cityModel in
                            // 城市
                            cityModel.level = 2
                            cityModel.pid = provinceModel.id
                        }
                    }
                }
                cityList = list
                if isShow {
                    cityView.dataSources = cityList
                    popup.bottomSheet(enableDrag: false) {
                        cityView
                    }
                }
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
    }
    
    
}

// MARK: - private
private extension LoginRegisterInfoController {
    
    func initNav() {
        // 设置初始导航栏透明度
        vhl_navBarBackgroundAlpha = 0
    }
    
    func initUI() {
        view.backgroundColor = .white
        
        let bgImageView = UIImageView(image: "ic_top_bg".toImage)
        view.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
        }
        
        view.addSubview(submitView)
        submitView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(124)
            make.bottom.equalToSuperview().offset(-xIphoneBottomSafeHeight)
        }
        submitView.submitButton.addTarget(self, action: #selector(registerAction), for: .touchUpInside)
        
        scrollView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(xIphoneNavStatusBarHeight)
            make.bottom.equalTo(submitView.snp.top).offset(-4)
        }
        
        countryView.country = country
        scrollView.addSubview(countryView)
        countryView.snp.makeConstraints { make in
            make.top.left.equalToSuperview()
            make.width.equalTo(xScreenW)
        }
        countryView.didSelectedCountryBlock = { [self] model in
            // 0：中国，1：其他
            country = (model.id == 0 ? 0: 1)
        }
        
        scrollView.addSubview(areaView)
        areaView.snp.makeConstraints { make in
            make.top.equalTo(countryView.snp.bottom)
            make.left.equalToSuperview()
            make.width.equalTo(xScreenW)
        }
        areaView.didClickSelecteAreaListBlock = { [self] in
            // 弹框
            if cityList.count == 0 {
                getSelectedCityList(isShow: true)
                return
            }
            
            cityView.dataSources = cityList
            popup.bottomSheet(enableDrag: false) {
                cityView
            }
        }
        
        cityView.closeBlock = {
            self.popup.dismissPopup()
        }
        cityView.didSelectedBlock = { (id, name) in
            if id == -1 {
                xLog("不限")
            } else {
                xLog("城市信息  id:\(id) name:\(name)")
            }
            self.city = id
            self.areaView.contentTextField.text = name
            self.popup.dismissPopup()
        }
        
        scrollView.addSubview(identityView)
        identityView.snp.makeConstraints { make in
            make.top.equalTo(areaView.snp.bottom)
            make.left.equalToSuperview()
            make.width.equalTo(xScreenW)
        }
        identityView.didSelectedIdentityBlock = { model in
            self.identityId = model.id
        }
        
        scrollView.addSubview(companyView)
        companyView.snp.makeConstraints { make in
            make.top.equalTo(identityView.snp.bottom)
            make.left.equalToSuperview()
            make.width.equalTo(xScreenW)
        }
        companyView.textDidChangeBlock = { text in
            self.nickname = text
        }
        
//        scrollView.addSubview(avatarView)
//        avatarView.snp.makeConstraints { make in
//            make.top.equalTo(companyView.snp.bottom)
//            make.left.equalToSuperview()
//            make.width.equalTo(xScreenW)
//        }
//        avatarView.avatarButton.addTarget(self, action: #selector(selectImageFromLibrary), for: .touchUpInside)
        
        updateScrollViewContentSize()
    }
    
    private func updateScrollViewContentSize() {
        view.layoutIfNeeded()
        scrollView.contentSize = CGSizeMake(xScreenW, CGRectGetMaxY(companyView.frame) + 10)
    }
}

// MARK: - UIImagePickerControllerDelegate
//extension LoginRegisterInfoController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//    
//    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//        if let editedImage = info[.editedImage] as? UIImage {
//            // 使用编辑后的图片（如果有的话）
//            print("使用编辑后的图片")
//            avatarView.avatarButton.setBackgroundImage(editedImage, for: .normal)
//            uploadAvatar(image: editedImage)
//            
//        } else if let originalImage = info[.originalImage] as? UIImage {
//            // 使用原始图片（如果没有编辑的话）
//            print("使用原始图片")
//            avatarView.avatarButton.setBackgroundImage(originalImage, for: .normal)
//            uploadAvatar(image: originalImage)
//        }
//        dismiss(animated: true, completion: nil) // 关闭图片选择器
//    }
//    
//    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//        dismiss(animated: true, completion: nil) // 用户取消选择，关闭图片选择器
//    }
//}
